const web = {};
module.exports = web;

/**
 * web端设置剪切板方案
 */
web.setClipboardData = function ({ data }) {
    if (document) {
        const input = data;
        const el = document.createElement('textarea');

        el.value = input;

        // Prevent keyboard from showing on mobile
        el.setAttribute('readonly', '');

        el.style.contain = 'strict';
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        el.style.fontSize = '12pt'; // Prevent zooming on iOS

        const selection = getSelection();
        let originalRange = false;
        if (selection.rangeCount > 0) {
            originalRange = selection.getRangeAt(0);
        }

        document.body.appendChild(el);
        el.select();

        // Explicit selection workaround for iOS
        el.selectionStart = 0;
        el.selectionEnd = input.length;

        let success = false;
        try {
            success = document.execCommand('copy');
        } catch (err) { }

        document.body.removeChild(el);

        if (originalRange) {
            selection.removeAllRanges();
            selection.addRange(originalRange);
        }

        return success;
    }
};

/**
 * 将URL中的参数字符串转成object
 */
web.parseQueryString = function (queryStr) {
    if (!queryStr) { return {}; }
    queryStr = queryStr.split('?').pop();
    if (!queryStr) { return {}; }

    queryStr = decodeURIComponent(queryStr);

    var arrQuery = queryStr.split("&"), oQuery = {};
    for (var i = 0, ii = arrQuery.length; i < ii; i++) {
        var arrTmp = arrQuery[i].split("=");
        if (arrTmp.length === 2) {
            oQuery[arrTmp[0]] = arrTmp[1];
        }
    }
    return oQuery;
};

/**
 * 将object转成URL参数的格式
 */
web.stringifyQueryString = function (params) {
    if (typeof params === 'string') {
        return params;
    } else if (params === null || typeof params !== 'object') {
        return encodeURIComponent(JSON.stringify(params));
    } else {
        var qs = '';
        for (var i in params) {
            if (params[i] !== undefined) {
                if (typeof params[i] === 'object') {
                    qs += '&' + i + '=' + encodeURIComponent(JSON.stringify(params[i]));
                } else {
                    qs += '&' + i + '=' + encodeURIComponent(params[i]);
                }
            }
        }
        return qs.slice(1);
    }
}

/**
 * 获得URL中的某个参数
 */
web.getUrlQueryValue = function (name) {
    var vaule = this.getQueryObject(location.search.slice(1))[name];
    return vaule ? decodeURIComponent(vaule) : vaule;
};